import 'package:geolocator/geolocator.dart';
import 'package:dio/dio.dart';

class WeatherService {
  final String apiKey = 'a0d545209b7940e891a60c1ef1a50fc9'; // 替换为你的 API 密钥
  final Dio dio = Dio();

  Future<Map<String, String>?> getWeather() async {
    try {
      Position position = await _getCurrentLocation();
      if (position != null) {
        print('Current location: ${position.latitude}, ${position.longitude}');
        Map<String, String>? locationInformation=await _fetchLocationId(position.latitude, position.longitude);
        String? locationId = locationInformation?['id'];
        if (locationId != null) {
          Map<String, String>?weather=await _fetchWeather(locationId);
          weather?['City']=locationInformation!['name']!;
          return weather;
        }
      }
    } catch (e) {
      print('Error getting weather: $e');
    }
    return null;
  }

  Future<Position> _getCurrentLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      throw Exception('Location services are disabled.');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        throw Exception('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      throw Exception('Location permissions are permanently denied.');
    }

    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }
  Future<Map<String,String>?> _fetchLocationId(double lat, double lon) async {
    final url = 'https://geoapi.qweather.com/v2/city/lookup';
    final formattedLat = lat.toStringAsFixed(2); // 格式化纬度到小数点后两位
    final formattedLon = lon.toStringAsFixed(2); // 格式化经度到小数点后两位
    final queryParameters = {
      'location': '$formattedLon,$formattedLat', // 经度在前，纬度在后
      'key': apiKey,
    };

    try {
      print('Fetching location ID with URL: $url and parameters: $queryParameters');
      final response = await dio.get(url, queryParameters: queryParameters);
      print('Response status code: ${response.statusCode}');
      print('Response data: ${response.data}');
      if (response.statusCode == 200) {
        final data = response.data;
        if (data['code'] == '200' && data['location'] != null && data['location'].isNotEmpty) {
          return {'id':data['location'][0]['id'],'name':data['location'][0]['adm2']+' '+data['location'][0]['name']};
        } else {
          print('获取地理位置信息失败: ${data['code']}');
          return null;
        }
      } else {
        print('请求失败: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('网络异常: $e');
      return null;
    }
  }

  Future<Map<String, String>?> _fetchWeather(String locationId) async {
    final url = 'https://devapi.qweather.com/v7/weather/now';
    final queryParameters = {
      'location': locationId,
      'key': apiKey,
      'lang': 'zh', // 可选参数，多语言设置
      'unit': 'm',  // 可选参数，单位设置
    };

    try {
      print('Fetching weather with URL: $url and parameters: $queryParameters');
      final response = await dio.get(url, queryParameters: queryParameters);
      print('Weather response status code: ${response.statusCode}');
      print('Weather response data: ${response.data}');
      if (response.statusCode == 200) {
        final data = response.data;
        if (data['code'] == '200') {
          String? cityName = data['now']?['name'];
          String? temperature = data['now']?['temp']?.toString() ?? 'N/A';
          String? weatherText = data['now']?['text'] ?? 'N/A';

          print('City: $cityName, Temperature: $temperature °C, Weather: $weatherText');
          return {
            'City': cityName ?? 'Unknown',
            'Temperature': '$temperature °C',
            'Weather': weatherText??'',
          };
        } else {
          print('获取天气信息失败: ${data['code']}');
        }
      } else {
        print('请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('网络异常: $e');
    }
    return null;
  }
}
